import { AUTH_USER_TOKEN_KEY, DEVICE_ID, LOGIN_CODE } from '@/config/constant'
import { IResponse } from '@/types/global'
import axios, { AxiosError, AxiosResponse } from 'axios'
import { triggerAdminLogout } from '../events/login'

axios.interceptors.request.use(
    (config) => {
        // 设置基础URL
        config.baseURL = import.meta.env.VITE_BASE_URL
        // 设置App-Id
        config.headers['App-Id'] = import.meta.env.VITE_APP_ID
        // 设置Authorization
        config.headers.Authorization = `Bearer ${localStorage.getItem(
            AUTH_USER_TOKEN_KEY
        )}`
        // 设置设备指纹
        config.headers['Device-Id'] = localStorage.getItem(DEVICE_ID)

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
axios.interceptors.response.use(
    async (response: AxiosResponse<IResponse<any>>): Promise<any> => {
        // 获取响应数据
        const res: IResponse<any> = response.data

        // 如果响应数据中code不为0，抛出响应数据
        if (res.code) {
            if (LOGIN_CODE.includes(res.code)) {
                triggerAdminLogout()
            }

            throw res
        }

        // 否则返回响应数据的data字段
        return res.data
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)
